<?php

namespace App\Repositories\Admin;


use App\Http\Resources\Admin\MenusResource;
use App\Repositories\BaseRepository;
use App\Services\MenusService;

class MenusRepository extends BaseRepository
{
    /**
     * @var MenusService
     */
    private $service;


    /**
     * MenusService constructor.
     * @param MenusService $service
     */
    public function __construct(MenusService $service)
    {
        $this->service = $service;
    }


    /**
     * @param array $map
     * @param null $role
     * @return array|\Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function handleMenus($map = [], $role = null)
    {
        // 获取所有的目录
        $map['parent_id'] = 0;
        $menus = $this->service->makeModel()
            ->select('id', 'icon', 'parent_id', 'name')
            ->filter($map)
            ->orderBy('weight', 'desc')
            ->get();
        if (isset($map['show_child']) && !$map['show_child']) {
            return MenusResource::collection($menus);
        }
        $menus->load('children');
        return $this->handleCheck($menus, $role ? $role->menus()->pluck('id')->toArray() : null);
    }


    /**
     * 获取选择的目录
     * @param $menus
     * @param $roleMenu
     * @return array
     */
    public function handleCheck($menus, $roleMenu)
    {
        $data = [];
        foreach ($menus as $menu) {
            $menuChecked = in_array($menu->id, $roleMenu);
            $map = [
                'checked' => false,
                'id' => $menu->id,
                'name' => $menu->name,
                'parent_id' => $menu->parent_id,
            ];
            foreach ($menu->children as $key => $child) {
                $checked = in_array($child->id, $roleMenu);
                $childrenMap = [
                    'id' => $child->id,
                    'name' => $child->name,
                    'parent_id' => $child->parent_id,
                    'children' => []
                ];
                foreach ($child->children as $k => $c) {
                    $cChecked = in_array($c->id, $roleMenu);
                    $childrenMap['children'][] = [
                        'id' => $c->id,
                        'checked' => $cChecked,
                        'name' => $c->name,
                        'parent_id' => $c->parent_id
                    ];
                    if ($cChecked && !$checked) {
                        $checked = true;
                        $menuChecked = true;
                    }
                }
                $childrenMap['checked'] = $checked;
                $map['children'][] = $childrenMap;
            }
            $map['checked'] = $menuChecked;
            $data[] = $map;
        }
        return $data;
    }
}
